import type { ConfigEnv, UserConfig } from 'vite';
import { loadEnv } from 'vite';
import { resolve } from 'path';
import dayjs from 'dayjs';
import { wrapperEnv } from './build/utils';
import { OUTPUT_DIR } from './build/constant';
import pkg from './package.json';
import { createVitePlugins } from './build/plugin';
import { generateModifyVars } from './build/generateModifyVars';

function pathResolve(dir: string) {
	return resolve(process.cwd(), '.', dir);
}

const { dependencies, devDependencies, name, version } = pkg;
const __APP_INFO__ = {
	pkg: { dependencies, devDependencies, name, version },
	lastBuildTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
};

export default ({ command, mode }: ConfigEnv): UserConfig => {
	const root = process.cwd();

	const env = loadEnv(mode, root);
	const viteEnv = wrapperEnv(env);
	const { VITE_PUBLIC_PATH, VITE_DROP_CONSOLE } = viteEnv;

	const isBuild = command === 'build';

	isBuild && console.warn('😘请确保已修改过版本号！');

	return {
		base: VITE_PUBLIC_PATH,
		root,
		resolve: {
			alias: [
				{
					find: 'vue-i18n',
					replacement: 'vue-i18n/dist/vue-i18n.cjs.js',
				},
				{
					find: '@',
					replacement: pathResolve('src'),
				},
				{
					find: '~',
					replacement: pathResolve('types'),
				},
				{
					find: '#',
					replacement: pathResolve('src/basicComp'),
				},
			],
		},
		server: {
			host: true,
			port: 5000,
			proxy: {
				'/v3-basic-api': {
					target: 'http://101.132.105.177:15051',
					changeOrigin: true,
					rewrite: path => path.replace(/^\/v3-basic-api/, ''),
				},
				'/upload': {
					target: 'http://101.132.105.177:18080',
					changeOrigin: true,
				},
			},
		},
		esbuild: {
			pure: VITE_DROP_CONSOLE ? ['console.log', 'debugger'] : [],
		},
		build: {
			target: 'es2015',
			outDir: OUTPUT_DIR,
			minify: 'terser',
			terserOptions: {
				compress: {
					keep_infinity: true,
					drop_console: VITE_DROP_CONSOLE,
				},
			},
			brotliSize: false,
			chunkSizeWarningLimit: 2000,
		},
		define: {
			__INTLIFY_PROD_DEVTOOLS__: false,
			__APP_INFO__: JSON.stringify(__APP_INFO__),
		},
		css: {
			preprocessorOptions: {
				less: {
					modifyVars: generateModifyVars(),
					javascriptEnabled: true,
				},
			},
		},
		plugins: createVitePlugins(viteEnv, isBuild),

		optimizeDeps: {
			include: ['@vue/runtime-core', '@vue/shared', '@iconify/iconify', 'ant-design-vue/es/locale/zh_CN'],
		},
	};
};
